import express from 'express'
import multer from 'multer'

const upload = multer({
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, './uploads/');
        },
        filename: function (req, file, cb) {
            var changedName = file.originalname//(new Date().getTime())+'-'+file.originalname;
            cb(null, changedName);
        }
    })
});
const router = express.Router()

router.get('/', (req, res) => {
    // console.log('客户ip', req.ip);
    if (req.ip == '::ffff:127.0.0.1') {
        // 管理员界面
        res.render('admin.html');

    } else {
        // 如果存在cookies，就读取其中的名称
        if (req.cookies.username) {
            // console.log('找到了cookie用户名:', req.cookies.username);
            res.render('index.html', {
                title: 'Socket.IO chat',
                name: req.cookies.username,
                something: 'something'
            })
        } else {
            // 否则进入登陆界面
            res.render('login.html');
        }
        
    }
})

// 登陆界面输入用户名，提交login的url请求（应当加入用户名重复逻辑）
router.post('/login', (req, res) => {
    let { username } = req.body;
    res.cookie('username', username, { maxAge: 24 * 3600 * 1000, signed: false });
    res.redirect('/');
})

router.get('/test',(req,res)=>{
    res.render('test.html')
})

router.post('/upload', upload.single('file'), (req, res) => {
    // console.log(req.file);
    res.status(200).json({
        fileName: req.file.filename,
        originalname: req.file.originalname,
        path: req.file.path
    })
});


export default router